﻿using Microsoft.EntityFrameworkCore;
using Mt.Site.Core.Editions;
using Mt.Site.Core.MultiTenancy;
using Mt.Site.EntityFrameworkCore;
using System.Linq;

namespace Mt.Site.Migrations.Seed.Tenants
{
    public class DefaultTenantBuilder
    {
        private readonly MtSiteDbContext _context;

        public DefaultTenantBuilder(MtSiteDbContext context)
        {
            _context = context;
        }

        public void Create(string defaultTenantName)
        {
            CreateDefaultTenant(defaultTenantName);
        }

        private void CreateDefaultTenant(string defaultTenantName)
        {
            //Default tenant

            var defaultTenant = _context.Tenants.IgnoreQueryFilters().FirstOrDefault(t => t.TenancyName == defaultTenantName);
            if (defaultTenant == null)
            {
                defaultTenant = new Tenant(defaultTenantName, defaultTenantName) ;

                var defaultEdition = _context.Editions.IgnoreQueryFilters().FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName);
                if (defaultEdition != null)
                {
                    defaultTenant.EditionId = defaultEdition.Id;
                }

                _context.Tenants.Add(defaultTenant);

                _context.SaveChanges();
            }
        }
    }
}
